package site.lanmushan.framework.query.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author Administrator
 */
@Slf4j
public class ImportExportDataUtil {

    public static void export(String fileName, String suffix, byte[] bytes) {
        BufferedOutputStream buff = null;
        ServletOutputStream outStr = null;
        try {
            HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
            response.setCharacterEncoding("utf-8");
            //设置响应的内容类型
            response.setContentType("text/plain");
            //设置文件的名称和格式
            fileName += LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String innerFileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
            response.addHeader("Content-Disposition", "attachment;filename="
                    + innerFileName
                    + suffix);
            outStr = response.getOutputStream();
            buff = new BufferedOutputStream(outStr);
            buff.write(bytes);
            buff.flush();
            buff.close();
        } catch (Exception e) {
            log.error(e.getLocalizedMessage(), e);
        } finally {
            try {
                buff.close();
                outStr.close();
            } catch (Exception e) {
            }
        }

    }
}
